package com.jdk7.mo.config;

import com.jdk7.mo.entity.Teacher;
import com.jdk7.mo.listener.BaseJobListener;
import com.jdk7.mo.process.TeacherItemProcessor;
import com.jdk7.mo.reader.TeacherFieldSetMapper;
import com.jdk7.mo.writer.TeacherItemWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

@Configuration
public class TeacherJobConfig {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    // begin reader, writer, and processor
    @Bean
    public FlatFileItemReader<Teacher> csvTeacherReader() {
        FlatFileItemReader<Teacher> reader = new FlatFileItemReader<Teacher>();
        reader.setResource(new ClassPathResource("csv/teacher.csv"));
        reader.setLinesToSkip(1);
        reader.setLineMapper(new DefaultLineMapper<Teacher>() {{
            setLineTokenizer(new DelimitedLineTokenizer() {{
                setNames(new String[]{"id", "name", "sex", "birthDate", "homeAddress", "school", "workingYears"});
            }});
            setFieldSetMapper(new TeacherFieldSetMapper());
        }});
        return reader;
    }


    @Bean
    ItemProcessor<Teacher, Teacher> csvTeacherProcessor() {
        return new TeacherItemProcessor();
    }

    @Bean
    public ItemWriter<Teacher> csvTeacherWriter() {
        TeacherItemWriter writer = new TeacherItemWriter();
        return writer;
    }
    // end reader, writer, and processor

    // begin job info
    @Bean
    public Step csvTeacherToDBStep() {
        return stepBuilderFactory.get("csvTeacherToDBStep")
                .<Teacher, Teacher>chunk(10)
                .reader(csvTeacherReader())
                .processor(csvTeacherProcessor())
                .writer(csvTeacherWriter())
                .build();
    }

    @Bean
    Job teacherJob(BaseJobListener listener) {
        return jobBuilderFactory.get("teacherJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener)
                .flow(csvTeacherToDBStep())
                .end()
                .build();
    }
    // end job info
}
